package com.sskj.hangqing.ui.activity;


import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.sskj.common.base.App;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.DisposUtil;
import com.sskj.hangqing.R;
import com.sskj.hangqing.R2;
import com.sskj.hangqing.bean.rxbus.MarketCoinBean;
import com.sskj.hangqing.presenter.MarketActivityPresenter;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.bean.BibiCoinType;
import com.sskj.lib.bean.CoinBean;
import com.sskj.lib.bean.TabItem;
import com.sskj.lib.bean.enums.ColorEnum;
import com.sskj.lib.box.LiveDataBus;
import com.sskj.lib.util.CoinUtil;
import com.sskj.lib.util.CommonUtil;
import com.sskj.lib.util.NumberUtil;
import com.sskj.lib.util.PopUtil;
import com.sskj.lib.widget.SpinnerPop;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.disposables.Disposable;

@Route(path = RConfig.HANG_MARKET)
public class MarketActivity extends BaseActivity<MarketActivityPresenter> {
    @Autowired
    String code;
    @Autowired
    String qu;
    @BindView(R2.id.tvTitle)
    TextView tvTitle;
    @BindView(R2.id.frameLayoutChart)
    FrameLayout frameLayoutChart;
    @BindView(R2.id.frameLayoutBottom)
    FrameLayout frameLayoutBottom;
    @BindView(R2.id.slidingTabLayout)
    CommonTabLayout slidingTabLayout;
    @BindView(R2.id.btTrade)
    Button btTrade;
    @BindView(R2.id.tvUSDT)
    TextView tvUSDT;
    @BindView(R2.id.tvHigh)
    TextView tvHigh;
    @BindView(R2.id.tvRMB)
    TextView tvRMB;
    @BindView(R2.id.tvRate)
    TextView tvRate;
    @BindView(R2.id.tvLow)
    TextView tvLow;
    @BindView(R2.id.tvVolume)
    TextView tvVolume;
    private SpinnerPop spinnerPop;
    private HashMap<Integer, Fragment> bottomMap;
    private int curPos;
    private Disposable spinnerDispo;


    @Override
    protected int getLayoutId() {
        return R.layout.hang_activity_market_scroll;
    }

    @Override
    public MarketActivityPresenter getPresenter() {
        return new MarketActivityPresenter();
    }

    @Override
    protected void initView() {
        ARouter.getInstance().inject(this);
        tvTitle.setText(TextUtils.isEmpty(code) ? "" : code.replace("_", "/").toUpperCase());
        ClickUtil.click(btTrade, () -> {
            RxBus.getDefault().post(new BibiCoinType(code, qu));
            LiveDataBus.get().with(RxBusCode.CHANGE_MAIN_TAB,Integer.class)
                    .postValue(2);
            finish();
        });
        getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.frameLayoutChart, (Fragment) ARouter.getInstance()
                        .build(RConfig.HANG_FRAGMENT_CHART)
                        .withString(Constans.CODE, code)
                        .withString(Constans.GOOD_TYPE, "minute")
                        .withBoolean(Constans.IS_CANDLE, false)
                        .navigation()
                )
                .commitAllowingStateLoss();

        ArrayList<Fragment> fragments = new ArrayList<>();
        fragments.add((Fragment) ARouter.getInstance()
                .build(RConfig.HANG_FRAGMENT_DEEPTH)
                .withString(Constans.CODE, code)
                .navigation());
        fragments.add((Fragment) ARouter.getInstance()
                .build(RConfig.HANG_FRAGMENT_TRADE)
                .withString(Constans.CODE, code)
                .navigation());
        fragments.add((Fragment) ARouter.getInstance()
                .build(RConfig.HANG_FRAGMENT_SUMMARY)
                .withString(Constans.CODE, code)
                .navigation());
        getSupportFragmentManager().beginTransaction()
                .add(R.id.frameLayoutBottom, fragments.get(0))
                .show(fragments.get(0))
                .commitAllowingStateLoss();
        bottomMap = new HashMap<>();
        bottomMap.put(0, fragments.get(0));
        curPos = 0;
        ArrayList<CustomTabEntity> tabItems = new ArrayList<>();
        tabItems.add(new TabItem(App.INSTANCE.getString(R.string.hangqingmarketActivity1), 0, 0));
        tabItems.add(new TabItem(App.INSTANCE.getString(R.string.hangqingmarketActivity2), 0, 0));
        tabItems.add(new TabItem(App.INSTANCE.getString(R.string.hangqingmarketActivity3), 0, 0));
        slidingTabLayout.setTabData(tabItems);
        slidingTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                if (bottomMap.get(position) == null) {
                    getSupportFragmentManager().beginTransaction()
                            .add(R.id.frameLayoutBottom, fragments.get(position))
                            .hide(fragments.get(curPos))
                            .show(fragments.get(position))
                            .commitAllowingStateLoss();
                    bottomMap.put(position, fragments.get(position));
                } else {
                    getSupportFragmentManager().beginTransaction()
                            .hide(fragments.get(curPos))
                            .show(fragments.get(position))
                            .commitAllowingStateLoss();
                }
                curPos = position;
            }

            @Override
            public void onTabReselect(int position) {

            }
        });


    }

    @Override
    protected void initData() {
        mPresenter.getData(code);
        LiveDataBus.get().with(RxBusCode.PUSH_COIN_BEAN, CoinBean.class)
                .observe(this, this::refreshCoin);
    }


    public void updateSpinner(List<CoinBean> data) {
        if (data == null || data.size() == 0) {
            return;
        }
        spinnerDispo = Flowable.fromIterable(data)
                .map(coinBean -> coinBean.getCode().toUpperCase())
                .toList()
                .subscribe(strings -> {
                    ClickUtil.click(tvTitle, () -> {
                        if (spinnerPop == null) {
                            spinnerPop = PopUtil.popSpinner(this, (recyclerView, position, v) -> {
                                spinnerPop.dismiss();
                                tvTitle.setText(strings.get(position).replace("_", "/").toUpperCase());
                                code = data.get(position).getCode();
                                mPresenter.getData(code);
                                LiveDataBus.get().with(RxBusCode.CHANGE_MARKET_CODE,MarketCoinBean.class)
                                        .postValue(new MarketCoinBean(code, qu));
                            }, strings);
                        }
                        spinnerPop.showPopupWindow(tvTitle);
                    });
                });
    }

    public void refreshCoin(CoinBean data) {
        if (data.getCode().equals(code)) {
            tvUSDT.setText(NumberUtil.keep(data.getPrice(), 8, true) + data.getRCode());
            tvRMB.setText(String.format("≈%s " + Constans.DANWEI, CommonUtil.dealCNY(data.getCnyPrice())));
            tvRate.setText(data.getChangeRate());
            tvLow.setText(CoinUtil.keepCoinPrice(code, data.getLow()));
            tvHigh.setText(CoinUtil.keepCoinPrice(code, data.getHigh()));
            tvVolume.setText(Double.valueOf(data.getVolume()).intValue() + "");
            tvUSDT.setTextColor(ContextCompat.getColor(App.INSTANCE, data.isUp() ? ColorEnum.UP.getColor() : ColorEnum.DOWN.getColor()));
            tvRate.setTextColor(ContextCompat.getColor(App.INSTANCE, data.isUp() ? ColorEnum.UP.getColor() : ColorEnum.DOWN.getColor()));
        }
    }

    @Override
    protected void onDestroy() {
        DisposUtil.close(spinnerDispo);
        super.onDestroy();
    }
}

